package com.xdd.app01;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class HandlerActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btn_start;
    private TextView tv_time;
    private Handler handler;
    int num = 30;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler);
        btn_start = findViewById(R.id.btn_start);
        tv_time = findViewById(R.id.tv_time);

        btn_start.setOnClickListener(this);

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message msg) {
                if (msg.what == 1) {
                    if (num <= 0) {
                        handler.removeMessages(1);
                    } else {
                        num--;
                        tv_time.setText(num + "s");
                        handler.sendEmptyMessageDelayed(1, 1000);
                    }

                }
                return false;
            }
        });


    }

    @Override
    public void onClick(View v) {
        if (num == 0) {
            btn_start.setClickable(true);
            num = 30;
        } else {
            handler.sendEmptyMessage(1);
            btn_start.setClickable(false);
        }
    }
}
